// pages/AddPart/AddPart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    manufacturerList: [],
    showPopup1: false, // 控制弹出层显示与隐藏
    partName: "",
    partcheack: true,
    sendImage: "",
    material: "", //材料
    postprocessing: "", //后处理
    // partNumber: "", //零件序号
    customerName: "", //客户姓名
    orderNumber: "", //订单号
    manufacturerNam: "", //厂家姓名
    partImage: "", //零件截图照片地址
    quantity: "", //数量
    blankingImg: "", //下料的照片地址
    blankingTime: "", //下料时间
    processingImage: "", //加工的照片地址 Preview
    processingTime: "", //加工时间
    handleImage: "", //后处理的照片地址
    handleTime: "", //后处理的时间
    qualityImg: "", //质检的照片地址
    qualityTime: "", //质检的时间
    deliveryTime: "", //发货时间
    remarks: "", //备注
    afterSale: "", //是否售后
    _id: ""
  },

  // 创建当前时间
  addTimeData() {
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, '0');
    const day = String(currentDate.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  onClosePopup1() {
    this.setData({
      showPopup1: false
    });
  },
  onCancelPicker1() {
    this.setData({
      showPopup1: false,
      manufacturerNam: ""
    });
    console.log(this.data.manufacturerNam)
  },
  onConfirmPicker1(event) {
    const {
      value
    } = event.detail;
    this.setData({
      showPopup1: false,
      manufacturerNam:value
    });
    console.log(this.data.manufacturerNam)
  },
  showPopup1() {
    this.setData({
      showPopup1: true
    });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      //获取厂家信息：
      this.fetchManufacturerList();
    const userinfo = wx.getStorageSync('userInfo')
    // console.log(userinfo.role)
    if (userinfo.role == 'Users') {
      this.setData({
        partcheack: false
      })
    } else if (userinfo.role == 'Manufacturer') {
      this.setData({
        partcheack: true
      })
    } else if (userinfo.role == 'Boss') {
      this.setData({
        partcheack: true
      })
    }
    const itemStr = options.item; // 获取传递过来的字符串
    const item = JSON.parse(itemStr); // 解析成对象
    console.log('接收到的部件对象：', item);
    this.setData({
      _id: item._id,
      partName: item.partName,
      sendImage: item.sendImage, //发货
      // partNumber: item.partNumber, //零件序号
      customerName: item.customerName, //客户姓名
      orderNumber: item.orderNumber, //订单号
      manufacturerNam: item.manufacturerNam, //厂家姓名
      partImage: item.partImage, //零件截图照片地址
      quantity: item.quantity, //数量
      blankingImg: item.blankingImg, //下料的照片地址
      blankingTime: item.blankingTime, //下料时间
      processingImage: item.processingImage, //加工的照片地址 Preview
      processingTime: item.processingTime, //加工时间
      handleImage: item.handleImage, //后处理的照片地址
      handleTime: item.handleTime, //后处理的时间
      qualityImg: item.qualityImg, //质检的照片地址
      qualityTime: item.qualityTime, //质检的时间
      deliveryTime: item.deliveryTime, //发货时间
      remarks: item.remarks, //备注
      afterSale: item.afterSale, //是否售后,
      material: item.material, //材料
      postprocessing: item.postprocessing //后处理
    })
    // console.log(this.data._id,'000000000000000')
  },
   //获取厂家信息：
   fetchManufacturerList: function () {
    wx.cloud.callFunction({
      name: 'getManufactorList',
      success: res => {
        if (res.result.success) {
          console.log(res.result.data)
          let nameArray2 = res.result.data.map(item => item.name)
          this.setData({
            manufacturerList: nameArray2
          });
        } else {
          wx.showToast({
            title: 'Failed to fetch data',
            icon: 'none'
          });
        }
      },
      fail: err => {
        // console.error('Failed to call cloud function:', err);
        wx.showToast({
          title: 'Failed to fetch data',
          icon: 'none'
        });
      }
    });
  },
  // 零件图片
  afterRead(event) {
    const {
      file
    } = event.detail;
    // 上传文件到云存储或调用云函数
    const timestamp = Date.now();
    wx.cloud.uploadFile({
      cloudPath: `${this.data.orderNumber}/${timestamp}`, // 上传至云端的路径
      filePath: file.url, // 小程序临时文件路径
      success: res => {
       
        this.setData({
          partImage: res.fileID,
        });
      },
      fail: console.error
    });
  },
  // 下料图片
  afterRead1(event) {
    const {
      file
    } = event.detail;
    // 上传文件到云存储或调用云函数
    const timestamp = Date.now();
    wx.cloud.uploadFile({
      cloudPath: `${this.data.orderNumber}/${timestamp}`, // 上传至云端的路径
      filePath: file.url, // 小程序临时文件路径
      success: res => {
        const addTime = this.addTimeData()
        this.setData({
          blankingImg: res.fileID,
          blankingTime:addTime
        });
      },
      fail: console.error
    });
  },
  // 加工图片
  afterRead2(event) {
    const {
      file
    } = event.detail;
    // 上传文件到云存储或调用云函数
    const timestamp = Date.now();
    wx.cloud.uploadFile({
      cloudPath: `${this.data.orderNumber}/${timestamp}`, // 上传至云端的路径
      filePath: file.url, // 小程序临时文件路径
      success: res => {
        const addTime = this.addTimeData()
        this.setData({
          processingImage: res.fileID,
          processingTime:addTime
        });
      },
      fail: console.error
    });
  },
  // 处理图片
  afterRead3(event) {
    const {
      file
    } = event.detail;
    // 上传文件到云存储或调用云函数
    const timestamp = Date.now();
    wx.cloud.uploadFile({
      cloudPath: `${this.data.orderNumber}/${timestamp}`, // 上传至云端的路径
      filePath: file.url, // 小程序临时文件路径
      success: res => {
        const addTime = this.addTimeData()
        this.setData({
          handleImage: res.fileID,
          handleTime:addTime
        });
      },
      fail: console.error
    });
  },
  // 质检图片
  afterRead4(event) {
    const {
      file
    } = event.detail;
    // 上传文件到云存储或调用云函数
    const timestamp = Date.now();
    wx.cloud.uploadFile({
      cloudPath: `${this.data.orderNumber}/${timestamp}`, // 上传至云端的路径
      filePath: file.url, // 小程序临时文件路径
      success: res => {
        const addTime = this.addTimeData()
        this.setData({
          qualityImg: res.fileID,
          qualityTime:addTime
        });
      },
      fail: console.error
    });
  },
  // 发货图片
  afterRead5(event) {
    const {
      file
    } = event.detail;
    // 上传文件到云存储或调用云函数
    const timestamp = Date.now();
    wx.cloud.uploadFile({
      cloudPath: `${this.data.orderNumber}/${timestamp}`, // 上传至云端的路径
      filePath: file.url, // 小程序临时文件路径
      success: res => {
        const addTime = this.addTimeData()
        this.setData({
          sendImage: res.fileID,
          deliveryTime:addTime
        });
      },
      fail: console.error
    });
  },
  // 返回上一个页面
  newAddOrder2() {
    wx.navigateTo({
      url: `/pages/PartsCatalog/PartsCatalog?orderNumber=${this.data.orderNumber}&afterSale=${this.data.afterSale}&user=${this.data.customerName}&manufactor=${this.data.manufacturerNam}`,
    })
  },

  // 编辑零件信息
  newAddOrder() {
    wx.cloud.callFunction({
      name: 'updatePartRecord',
      data: {
        _id: this.data._id,
        partName: this.data.partName,
        // partNumber: this.data.partNumber,
        customerName: this.data.customerName,
        orderNumber: this.data.orderNumber,
        manufacturerNam: this.data.manufacturerNam,
        partImage: this.data.partImage,
        quantity: this.data.quantity,
        blankingImg: this.data.blankingImg,
        blankingTime: this.data.blankingTime,
        processingImage: this.data.processingImage,
        processingTime: this.data.processingTime,
        handleImage: this.data.handleImage,
        handleTime: this.data.handleTime,
        qualityImg: this.data.qualityImg,
        qualityTime: this.data.qualityTime,
        deliveryTime: this.data.deliveryTime, //发货时间
        remarks: this.data.remarks,
        afterSale: this.data.afterSale,
        material: this.data.material, //材料
        postprocessing: this.data.postprocessing, //后处理
        sendImage: this.data.sendImage
      },
      success: res => {
        // console.log(res)
        if (res.result.success) {
          wx.showToast({
            title: '编辑零件信息成功',
            icon: 'success'
          });
          console.log(this.data.manufacturerNam, 898989)
          wx.navigateTo({
            url: `/pages/PartsCatalog/PartsCatalog?orderNumber=${this.data.orderNumber}&afterSale=${this.data.afterSale}&user=${this.data.customerName}&manufactor=${JSON.stringify(this.data.manufacturerNam)}`,
          })

          // 清空表单或跳转至其他页面 
        } else {
          wx.showToast({
            title: '云函数success了，但是零件信息更新失败',
            icon: 'none'
          });
        }
      },
      fail: err => {
        console.error('Failed to call cloud function:', err);
        wx.showToast({
          title: '零件信息更新失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})